package judesart.app.client.project.ui;

import java.util.List;

import judesart.app.client.project.ProjectController;
import judesart.app.client.project.ProjectControllerAsync;
import judesart.app.domain.Project;
import judesart.app.shared.SearchResult;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Composite;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ProjectsPanel extends Composite
{
    ProjectControllerAsync service = GWT.create(ProjectController.class);
    private final ProjectDetailsPanel detailsPanel;
    private final ContentPanel listPanel;

    public ProjectsPanel()
    {
        final ContentPanel mainPanel = new ContentPanel();
        mainPanel.setHeaderVisible(false);
        mainPanel.setFrame(false);
        mainPanel.setBorders(false);

        RpcProxy<List<Project>> proxy = new RpcProxy<List<Project>>()
        {
            @Override
            protected void load(Object loadConfig,
                    final AsyncCallback<List<Project>> callback)
            {
                getProjects(callback);
            }
        };

        ListLoader<ListLoadResult<Project>> loader = new BaseListLoader<ListLoadResult<Project>>(
                proxy, new BeanModelReader());
        ListStore<BeanModel> store = new ListStore<BeanModel>(loader);
        loader.load();

        listPanel = new ContentPanel();
        listPanel.setCollapsible(false);
        listPanel.setAnimCollapse(false);
        listPanel.setFrame(true);
        listPanel.setId("projects-view");
        listPanel.setHeading("Projects");
        listPanel.setWidth(800);
        listPanel.setHeight(513);
        listPanel.setBodyBorder(false);

        ListView<BeanModel> view = new ListView<BeanModel>()
        {
            @Override
            protected BeanModel prepareData(BeanModel model)
            {
                Project p = model.getBean();
                if (p.getSketchs() != null && p.getSketchs().size() > 0)
                {
                    model.set("photoId",
                            p.getSketchs().get(0).getImageId().toString());
                } else if (p.getPhotos() != null && p.getPhotos().size() > 0)
                {
                    model.set("photoId",
                            p.getPhotos().get(0).getImageId().toString());
                } else if (p.getArtworks() != null
                        && p.getArtworks().size() > 0)
                {
                    model.set("photoId",
                            p.getArtworks().get(0).getMainImageId().toString());
                } else
                {
                    model.set("photoId", "0");
                }
                return model;
            }
        };

        view.setTemplate(getTemplate());
        view.setStore(store);
        view.setItemSelector("div.thumb-wrap");
        view.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>()
                {

                    public void handleEvent(SelectionChangedEvent<BeanModel> be)
                    {
                        Log.debug(" handleEvent Selection ["
                                + be.getSelection().size() + "]");
                        if (be.getSelection().size() > 0)
                        {
                            Log.debug(" handleEvent 0 ["
                                    + be.getSelection().get(0).get("id") + "]");
                            open((Long) be.getSelection().get(0).get("id"));
                        }
                    }

                });
        view.setBorders(false);
        view.setHeight(430);
        listPanel.add(view);

        // cntntpnlProjects.add(panel);
        Button btnAddNew = new Button("Add New");
        btnAddNew.addSelectionListener(new SelectionListener<ButtonEvent>()
        {
            @Override
            public void componentSelected(ButtonEvent ce)
            {
                open(null);
            }
        });
        listPanel.addButton(btnAddNew);
        listPanel.setButtonAlign(HorizontalAlignment.RIGHT);
        mainPanel.add(listPanel);
        detailsPanel = new ProjectDetailsPanel();
        mainPanel.add(detailsPanel);
        // cntntpnlProjects.add(btnAddNew);
        // cntntpnlProjects.setSize("800", "400");
        initComponent(mainPanel);
        final Timer hideDetailsPanelTimer = new Timer()
        {
            @Override
            public void run()
            {
                detailsPanel.hide();
            }
        };
        hideDetailsPanelTimer.schedule(200);
    }

    private void open(Long projectId)
    {
        Log.debug("open -> [" + projectId + "]");
        detailsPanel.open(projectId);
        listPanel.hide();
        detailsPanel.show();
    }

    private native String getTemplate() /*-{
        return ['<tpl for=".">', 
        '<div style="float: left; width: 110px;" class="thumb-wrap" id="{id}">', 
        '<div class="thumb"><img src="/image?id={photoId}&size=100x100&crop=true" title="{title}"/></div>', 
        '<div style="text-align: center; width: 100%;">{title}</div>', 
        '</div>',
        '</tpl>', 
        '<div class="x-clear"></div>'].join("");
    }-*/;

    private void getProjects(final AsyncCallback<List<Project>> callback)
    {
        service.searchProjects(0, 500,
                new AsyncCallback<SearchResult<Project>>()
                {
                    @Override
                    public void onFailure(Throwable caught)
                    {
                        callback.onFailure(caught);
                    }

                    public void onSuccess(SearchResult<Project> result)
                    {
                        callback.onSuccess(result.getResults());
                    };
                });
    }
}
